#include <jni.h>
#include <string>
#include "ICanPlayer.h"
#include <android/native_window.h>
#include <android/native_window_jni.h>

extern "C" {
#include <libavcodec/avcodec.h>
}

JavaVM *javaVm = NULL;

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
    javaVm = vm;
    return JNI_VERSION_1_4;
}

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_icanlive_MainActivity_stringFromJNI(
        JNIEnv *env,
        jobject /* this */) {
    std::string hello = "Hello from C++";
    return env->NewStringUTF(avcodec_configuration());
}
extern "C"
JNIEXPORT jlong JNICALL
Java_com_example_icanlive_ICanPlayer_nativeInit(JNIEnv *env, jobject thiz) {
    ICanPlayer *iCanPlayer = new ICanPlayer(new JavaCallHelper(javaVm, env, thiz));
    return reinterpret_cast<jlong>(iCanPlayer);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_example_icanlive_ICanPlayer_setDataSource(JNIEnv *env, jobject thiz, jlong native_handler,
                                                   jstring path) {
    const char *path_ = env->GetStringUTFChars(path, 0);
    ICanPlayer *iCanPlayer = reinterpret_cast<ICanPlayer *>(native_handler);
    iCanPlayer->setDataSource(path_);
    env->ReleaseStringUTFChars(path, path_);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_example_icanlive_ICanPlayer_prepare(JNIEnv *env, jobject thiz, jlong native_handler) {
    ICanPlayer *iCanPlayer = reinterpret_cast<ICanPlayer *>(native_handler);
    iCanPlayer->prepare();
}
extern "C"
JNIEXPORT void JNICALL
Java_com_example_icanlive_ICanPlayer_start(JNIEnv *env, jobject thiz, jlong native_handler) {
    ICanPlayer *iCanPlayer = reinterpret_cast<ICanPlayer *>(native_handler);
    iCanPlayer->start();
}
extern "C"
JNIEXPORT void JNICALL
Java_com_example_icanlive_ICanPlayer_setSurface(JNIEnv *env, jobject thiz, jlong native_handler,
                                                jobject surface) {
    ICanPlayer *iCanPlayer = reinterpret_cast<ICanPlayer *>(native_handler);
    iCanPlayer->setWindow(ANativeWindow_fromSurface(env, surface));
}
extern "C"
JNIEXPORT void JNICALL
Java_com_example_icanlive_ICanPlayer_stop(JNIEnv *env, jobject thiz, jlong native_handler) {
    ICanPlayer *iCanPlayer = reinterpret_cast<ICanPlayer *>(native_handler);
    iCanPlayer->stop();
    delete iCanPlayer;
    iCanPlayer = NULL;
}